package cn.tedu.v6;

import java.io.*;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;

/**
 * Version 5    登录与退出  功能：可以加在V3
 *
 */

public class Server {

    private ServerSocket serverSocket;
    private static final Integer PORT=0202;
    private List<PrintWriter> allOut=new ArrayList<>();
    //1.私有化属性：存账号和密码
    private Map<String,String> userDatabase;


    public Server(){
        try {
            serverSocket=new ServerSocket(PORT);
            //创建Map对象
            userDatabase=new HashMap<>();
            userDatabase.put("海燕","123456");
            userDatabase.put("小宝","654321");
        } catch (BindException e){
            System.out.println("请检查端口号，被占用~");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {
            while(true) {
                System.out.println("等待客户端连接");
                Socket socket = serverSocket.accept();

                new Thread(new ClientHandler(socket)).start();
            }
        } catch (IOException e) {
            System.out.println("客户端链接断开链接~");
        } finally {
            if(serverSocket!=null&&!serverSocket.isClosed()){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    System.out.println("服务器关闭失败~~~");
                }
                System.out.println("服务器关闭成功~~Over");
            }
        }
    }

    public static void main(String[] args){
        new Server().start();
    }


    private synchronized void broadcastMessage(String message){
            for(PrintWriter pw: allOut){
                pw.println("消息广播："+message);
            }
    }

    private class ClientHandler implements Runnable {
        private Socket socket;
        private String ip;
        private PrintWriter pw;
        private BufferedReader br;
        //4.线程中：确定那个客户端--赋予功能
        private String username;
        private String password;

        public ClientHandler(Socket s) {
            this.socket = s;
            ip = socket.getInetAddress().getHostAddress();
            try {
                br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8"));
                pw=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF8")),true);

                synchronized (allOut){
                    allOut.add(pw);
                }
            } catch (IOException e) {
                System.out.println("客户端断开链接了~");
            }
        }
        //5.5 因为用户账号可能有很多，封装Login，传入参数判断
        private boolean Login(String user,String pass){
            return userDatabase.containsKey(user
            )&&userDatabase.get(user).equals(pass);
        }
        //6.handleChat 封装：读写功能  ---放入线程中
        private void handleChat(){
            new Thread(()->{
                try {
                    String message;
                    while ((message=br.readLine())!=null) {
                        System.out.println(ip+"客户端说：" + message);
                        System.out.print("服务器请输入：");
                        broadcastMessage(message);
                    }
                } catch (IOException e) {
                    System.out.println("客户端发来的消息断开了~");
                }
            }).start();

            Scanner input=new Scanner(System.in);

            while(true){
                System.out.println("服务器请输入：");
                String sme=input.nextLine();
                pw.println("服务器说："+sme);
            }
        }
        public void run() {
            try {
       //5.当客户端进行读写功能前，加入登录功能
       //交互问题：服务器--客户端发送：文本
       //        客户端--服务器接收：文本
       //5.1向客户端发送一个提示消息：请输入用户名：
       pw.println("请输入用户名：");
       //5.2客户端输入账号[服务器端读取]
       username=br.readLine();
       pw.println("请输入密码：");
       password=br.readLine();
       //5.3 服务器端：判断账号与密码
       //5.4 用户可能有很多个，封装方法 Login:判断账号密码
      if(Login(username,password)){
          pw.println("登录成功，欢迎进入XX牌聊天室");
          //聊天功能   封装方法：读写功能  handleChat
          handleChat();
      }else{
          pw.println("登录失败，用户名或者密码错误！");
          socket.close();  //关闭
      }

       } catch (IOException e){
                System.out.println("服务器端读写出问题！");
       } finally {
                synchronized (allOut){
                    allOut.remove(pw);
                }
                if(pw!=null)
                    pw.close();
                if (br != null)
                    try {
                        br.close();
                    } catch (IOException e) {
                        System.out.println("读入流断开链接~");
                    }
                if(socket!=null&&!socket.isClosed()){
                    System.out.println(ip+"客户端退出服务器链接~");
                    try {
                        socket.close();
                    } catch (IOException e) {
                        System.out.println(ip+"客户端退出链接异常~");
                    }
                }
            }
        }
    }
}













